package com.lgb.controller.admin;

import com.lgb.Service.AnnouncementService;
import com.lgb.Service.MessageService;
import com.lgb.Service.UserService;
import com.lgb.pojo.Announcement;
import com.lgb.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.xml.ws.spi.http.HttpContext;

@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    UserService userService ;

    @Autowired
    MessageService messageService;

    @Autowired
    AnnouncementService announcementService;


    //跳转到登录页面
    @GetMapping
    public String loginPage(){
        return "admin/login";
    }

    //接收传递而来的参数并判断
    @PostMapping("/login")
    public String Login(@RequestParam String username ,
                        @RequestParam String password ,
                        HttpSession session,
                        RedirectAttributes attributes,
                        Model model){
        //查询用户
        User user= userService.checkUsers(username,password);
        //如果查询结果不为空
        if (user != null){
            //将密码设为null
            user.setPassword(null);
            //将参数放入session域,并返回后台主页
            session.setAttribute("user" ,user);
            //接收用户留言
            model.addAttribute("messages" , messageService.listMessage());
            //接收公告内容
            model.addAttribute("announcement" , announcementService.getOnlyone());
            return "admin/admin_index";
        }else {
            //提示登录失败
            attributes.addFlashAttribute("message" , "用户名或密码错误");
            //否则重定向到登录页面
            return "redirect:/admin";
        }
    }

    //跳转到后台首页(无需登录)
    @RequestMapping("/admin_index")
    public String admin_index(Model model){
        //接收用户留言
        model.addAttribute("messages" , messageService.listMessage());
        //接收公告内容
        model.addAttribute("announcement" , announcementService.getOnlyone());
        return "admin/admin_index";
    }

    //注销用户
    @GetMapping("/logout")
    public String logout(HttpSession session){
        //清空session域并返回登录
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
